
import os
from common import close_connection, factory_connection, get_fcodebyorder,waterfall_connection

home_dir = os.path.expanduser("~")
file_path = os.path.join(home_dir, 'Downloads', 'order.tsv')
sql_list = ['wf','pn','peach','meow','colorful','newlook']



def update_product(factory_code,order_no):
    print(f"{factory_code}\t{order_no}")
    connection = factory_connection(factory_code)
    cursor = connection.cursor()
    cursor.execute(f'SELECT id,flag from opr_product WHERE pickup_id in (SELECT id FROM opr_pickup WHERE order_no = "{order_no}") and flag & 512 != 512')
    results = cursor.fetchall()
    for row in results:
        product_id = row[0]
        flag = row[1]
        print(f"{product_id}\t{flag}")
        cursor.execute(f'UPDATE opr_product set `comment` = "必须重点质检",flag = {flag} | 2048 where id = {product_id}')
        connection.commit()
    close_connection(connection)

def update_shipment(code,shipment_no,out_time):
    connection = factory_connection(code)
    cursor = connection.cursor()
    cursor.execute(f'UPDATE opr_shipment set `status` = "8",modify_at = "{out_time}" where ch_shipment_no = "{shipment_no}"')
    connection.commit()
    close_connection(connection)









def get_out_time(shipment_no):
    connection = waterfall_connection()
    cursor = connection.cursor()
    for item in sql_list:
        cursor.execute(
            f"SELECT out_factory_time FROM {item}_order.ffl_shipment WHERE `no` = '{shipment_no}'")
        result = cursor.fetchone()
        if result:
            print(item)
            out_time = result[0]
            return out_time
    close_connection(connection)


with open(file_path, 'r') as file:
    lines = file.readlines()

    for line in lines:
        splited = line.split(" ")
        code = splited[1].strip()
        shipment_no = splited[2].strip()
        print(f"{code}\t{shipment_no}")
        out_time = get_out_time(shipment_no)
        update_shipment(code,shipment_no,out_time)
        #update_product(fcode, order_no)  # 将此行缩进到循环内 DM030952662370802 xayx ROC31042951750692 ORDERING


